<template>
  <div class="problem-management-container">
    <!-- 问题列表表格 -->
    <el-table
      :data="problemList"
      style="width: 100%"
      border
      stripe
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="userId" label="用户ID" width="120" />
      <el-table-column prop="question" label="问题描述" min-width="200" />
      
      <!-- 图片展示 -->
      <el-table-column label="问题图片" width="149">
        <template #default="scope">
          <div v-if="scope.row.files && scope.row.files.length > 0" style="display: flex; flex-wrap: wrap; gap: 4px;">
            <el-image
              v-for="(pic) in scope.row.files"
              :key="pic.id"
              style="width: 60px; height: 60px; cursor: pointer;"
              :src="pic.url"
              :preview-src-list="scope.row.files.map(item => item.url)"
              fit="cover"
              preview-teleported
            />
          </div>
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160" />
      <!-- 操作列 -->
      <el-table-column label="操作" width="80">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleReply(scope.row)"
          >
            回复
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>

    <!-- 回复弹窗 -->
    <el-dialog
      v-model="replyDialogVisible"
      title="回复用户问题"
      width="500px"
      center
    >
      <el-form :model="replyForm" label-width="80px">
        <el-form-item label="用户ID">
          <el-input v-model="replyForm.userId" disabled />
        </el-form-item>
        <el-form-item label="问题内容">
          <el-input v-model="replyForm.question" type="textarea" :rows="3" disabled />
        </el-form-item>
        <el-form-item label="客服回复" required>
          <el-input
            v-model="replyForm.result"
            type="textarea"
            :rows="4"
            placeholder="请输入您的回复内容"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="replyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReply" :loading="submitting">
          提交回复
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 导入API
import { getUserProblemApi, updateUserProblemApi,getPictureUrlApi } from '../../api/System'

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const submitting = ref(false)

// 问题列表数据
const problemList = ref([])

// 回复弹窗控制
const replyDialogVisible = ref(false)
const replyForm = ref({
  id: null,
  userId: '',
  question: '',
  result: ''
})

// 获取问题列表
const fetchProblemList = async () => {
  loading.value = true
  try {
    const res = await getUserProblemApi(currentPage.value, pageSize.value)
    if (res.code === 1 && res.data) {
      const data = res.data
      
      // 处理图片URL - 根据新的图片API响应格式
      const list = await Promise.all(data.rows.map(async (item) => {
        const processedItem = { ...item }
        
        // 如果有图片ID列表
        if (item.picture) {
          try {
            // 直接使用图片API返回的完整数据
            const picIds = item.picture.split(',').map(id => parseInt(id))
            const picRes = await getPictureUrlApi(picIds,item.userId)
            
            if (picRes.code === 1 && Array.isArray(picRes.data)) {
              processedItem.files = picRes.data
            } else {
              processedItem.files = []
            }
          } catch (error) {
            console.error('获取图片失败:', error)
            processedItem.files = []
          }
        } else {
          processedItem.files = []
        }
        
        return processedItem
      }))
      
      problemList.value = list
      total.value = data.total
    } else {
      ElMessage.error(res.message || '获取问题列表失败')
    }
  } catch (error) {
    console.error('请求异常:', error)
    ElMessage.error('网络错误，获取问题列表失败')
  } finally {
    loading.value = false
  }
}

// 打开回复弹窗
const handleReply = (row) => {
  replyForm.value = {
    id: row.id,
    userId: row.userId,
    question: row.question,
    result: row.result || ''
  }
  replyDialogVisible.value = true
}

// 提交回复
const submitReply = async () => {
  if (!replyForm.value.result.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }

  submitting.value = true
  try {
    const params = {
      id: replyForm.value.id,
      userId: replyForm.value.userId,
      result: replyForm.value.result.trim()
    }
    
    const res = await updateUserProblemApi(params)
    if (res.code === 1) {
      ElMessage.success('回复成功')
      replyDialogVisible.value = false
      // 刷新列表
      fetchProblemList()
    } else {
      ElMessage.error(res.message || '回复失败')
    }
  } catch (error) {
    console.error('提交回复失败:', error)
    ElMessage.error('网络错误，提交回复失败')
  } finally {
    submitting.value = false
  }
}

// 分页大小改变
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  fetchProblemList()
}

// 当前页改变
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  fetchProblemList()
}

// 页面加载时获取数据
onMounted(() => {
  fetchProblemList()
})
</script>

<style scoped>
.problem-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

h2 {
  margin-bottom: 20px;
  color: #303133;
  font-weight: 500;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .problem-management-container {
    padding: 10px;
  }
  
  :deep(.el-table) {
    font-size: 14px;
  }
  
  :deep(.el-table .cell) {
    padding: 6px 2px;
  }
}
</style>